import { Record, Map } from 'immutable';
import { createList } from './node';
import generateKey from '../utils/generate-key';
import Style from './style';
import Position from './position';

const DEFAULTS = {
  data: Map(),
  key: undefined,
  nodes: undefined,
  type: undefined,
  style: undefined,
  position: Position.create(),
  object: undefined,
};

class Block extends Record(DEFAULTS) {
  static create(attr = {}) {
    return Block.fromJSON(attr);
  }

  static fromJSON(object = {}) {
    if (Block.isBlock(object)) {
      return object;
    }
    const {
      data = {},
      key = generateKey(),
      nodes = [],
      style = {},
      type,
      position = {},
    } = object;
    return new Block({
      data: Map(data),
      style: Style.create(style),
      key,
      nodes: createList(nodes),
      type,
      position: Position.create(position),
      object: 'block',
    });
  }
}

Block.prototype.__block__ = true;
export default Block;
